<!-- 2023-08-07 用户提出，不允许修改行列标题、不允许增加/减少行列 -->
<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>砖砌体结构抗力修正系数Ci值</h4>
			<div class="buttonGroup">
				<el-button type="primary" @click="handleEditBrickTableHeader">
					{{ isEditTableHeader ? '保存表头' : '修改表头' }}
				</el-button>
				<!-- <el-button type="primary" @click="handleBrickBatchDelete">删除</el-button> -->
				<!-- <el-button type="primary" @click="handleBrickApply">应用</el-button> -->
			</div>
			<div class="table-content">
				<!-- <div class="table-left"> -->
					<el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
						:row-class-name="tableRowClassName">
						<el-table-column type="selection" />
						<el-table-column type="index" label="序号" width="80" />
						<el-table-column prop="condition" header-align="center" label="条件" width="480">
							<template #default="scope">
								<span>{{ scope.row.condition }}</span>
								<!-- <span v-if="!scope.row.isEdit">{{ scope.row.condition }}</span>
								<el-input v-else v-model="scope.row.condition" size="small"></el-input> -->
							</template>
						</el-table-column>
						<el-table-column header-align="center" label="修正系数Ci">
							<template v-if="tableColumns && tableColumns.length > 0">
								<el-table-column v-for="(item, index) in tableColumns" :key="index" :prop="item.filedProp"
									:label="item.filedName" header-align="center" align="center"
									:class-name="item.defaultData == '1' ? 'add-column' : ''">
									<template #header>
										<!-- 新增列复选框形式 -->
										<el-checkbox v-if="item.defaultData == '1'" v-model="item.checked">&nbsp;</el-checkbox>
										<!-- 基础列形式 -->
										<el-input v-if='isEditTableHeader' v-model="item.filedName" size="small" placeholder="输入表头" style="width: 70%;" />
										<span v-else>{{ item.filedName }}</span>
									</template>
									<template #default="scope">
										<span v-if="!scope.row.isEdit">{{ scope.row[item.filedProp] }}</span>
										<el-input v-else v-model="scope.row[item.filedProp]" size="small"></el-input>
									</template>
								</el-table-column>
							</template>
						</el-table-column>
						<el-table-column label="操作" fixed="right" width="120">
							<template #default="scope">
								<el-button type="text" size="small" @click="handleBrickModify(scope.$index, scope.row)">
									{{ scope.row.isEdit ? '应用' : '修改' }}
								</el-button>
								<!-- <el-button type="text" size="small" @click="handleBrickDelete(scope.$index, scope.row)">删除</el-button> -->
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-button class="add" style="width: 100%" plain @click="handleBrickAdd()">
						<el-icon style="vertical-align: middle">
							<Plus />
						</el-icon>
					</el-button> -->
				<!-- </div> -->
				<!-- <div class="table-right">
					<el-button class="add" plain @click="handleBrickColumnAdd()">
						<el-icon style="vertical-align: middle">
							<Plus />
						</el-icon>
					</el-button>
				</div> -->
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 获取当前实例
const { proxy } = getCurrentInstance();
// 引入接口
import { getAllZqtCi, saveZqtCi, deleteZqtCiById } from "@/api/vulnerModelManagement/brickMasonryRelation.js";
// 是否修改表头
const isEditTableHeader = ref(false);
// 表格
const tableData = ref([]);
const multipleSelection = ref([]);
const tableColumns = ref(
	[
		// {
		//     filedName: '满足',
		//     filedProp: 'amend1Satisfy'
		// },
		// {
		//     filedName: '不满足',
		//     filedProp: 'amend1Dissatisfy'
		// }
	]
)
//修改表头
const handleEditBrickTableHeader = () => {
	if (isEditTableHeader.value) { // 修改表头
		const paramsp = {
			zqtEntity: [],
			dynamicFieldsEntity: []
		}
		let flag = tableColumns.value.every(item=>(item.filedName&&item.filedName!=''))
		if(!flag){
			proxy.$modal.msgWarning('表头名称不能为空！')
			return;
		}
		tableColumns.value.forEach(item => {
			paramsp.dynamicFieldsEntity.push({
				cbrsId: item.cbrsId, //id
				cbrsKey: item.cbrsKey, //表名
				cbrsColumn: item.cbrsColumn, //列
				info: item.filedName, //字段名称
			})
		})
		saveZqtCi(paramsp).then((res) => {
			if (res.code === 200) {
				ElMessage({
					type: 'success',
					message: '添加成功!'
				});
				isEditTableHeader.value = false;
			}
		}).catch(err => {
			console.log(err);
		}
		);
	} else {
		isEditTableHeader.value = true;
	}
}
//修改 保存
const handleBrickModify = (index, row) => {
    if (row.isEdit) { // 编辑状态点击时，代表保存
        let isValid = true; // 用于标记所有输入是否有效
        for (const key in row) {
            if (Object.hasOwnProperty.call(row, key)) {
                if (key !== 'isEdit' && key !== 'isNew' && (key === 'dynamicField-1' || key === 'dynamicField-null')) {
                    console.log(key);
                    const element = row[key];
                    if (element === '' || element === null) {
                        ElMessage({
                            type: 'warning',
                            message: '请填写数据!'
                        });
                        isValid = false;
                        break; // 一旦发现无效数据，立即退出循环
                    }
                    // 验证是否为数值
                    if (!/^(-?\d+(\.\d+)?)$/.test(element)) {
                        ElMessage({
                            type: 'warning',
                            message: '请输入有效的数值!'
                        });
                        isValid = false;
                        break; // 一旦发现无效数据，立即退出循环
                    }
                }
            }
        }
        if (isValid) {
            onAddOrUpdateRows(row);
        }
    } else {
        row.isEdit = true;
    }
};

// 表格选择事件
const handleSelectionChange = (val) => {
	multipleSelection.value = val;
}
// 表格行状态
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.defaultData == '1') {
		return 'add-row';
	} else {
		return '';
	}
}
//删除单行
const handleBrickDelete = (index, row) => {
	//删除
	ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		if (row.cbrmIds) {
			await onDeleteRows(row.cbrmIds.join(','), '');
		} else {
			tableData.value.splice(index, 1);
		}
		onSearch();
	}).catch((error) => {
		console.error(error)
		ElMessage({
			type: 'info',
			message: '已取消删除'
		});
	});
}
//删除多行
const handleBrickBatchDelete = () => {
	//删除
	ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		let ids = []
		multipleSelection.value.forEach(item => { ids = ids.concat(item.cbrmIds) })
		const arrangeIds = []
		tableColumns.value.forEach(item => {
			if (item.defaultData === "1" && item.checked) {
				arrangeIds.push(item.cbrsId)
			}
		})
		await onDeleteRows(ids.join(','), arrangeIds.join(','))
		onSearch()
	}).catch((error) => {
		console.error(error)
		ElMessage({
			type: 'info',
			message: '已取消删除'
		})
	})
}
//新增行事件
const handleBrickAdd = async () => {
	const newObj = { condition: '', isEdit: true, isNew: true }
	tableColumns.value.forEach(item => {
		newObj[item.filedProp] = ''
	})
	tableData.value.push(newObj)
}
//新增列事件
const handleBrickColumnAdd = async () => {
	await onAddColumn()
}
//查询
const onSearch = () => {
	const paramsp = { titleName: '砖砌体结构抗力修正系数Ci值' }
	// 砖砌体结构抗力修正系数Ci值表查询
	getAllZqtCi(paramsp).then((res) => {
		if (res.code === 200) {
			buildTableColum(res.data.dynamicFieldsEntity)
			buildTableData(res.data.zqtEntity)
		}
	}).catch(err => {
		console.log(err);
	});
}
// 构建砖砌体结构抗力修正系数Ci值表格的动态列结构
const buildTableColum = (dynamicFieldsEntity) => {
	tableColumns.value = [];
	dynamicFieldsEntity.forEach(item => {
		tableColumns.value.push({
			filedName: item.info,
			filedProp: 'dynamicField-' + item.cbrsColumn,
			cbrsColumn: item.cbrsColumn,
			cbrsId: item.cbrsId,
			cbrsKey: item.cbrsKey,
			checked: false,
			defaultData: item.defaultData
		})
	})
}
// 构建砖砌体结构抗力修正系数Ci值表格的数据
const buildTableData = (zqtEntity) => {
	tableData.value = [];
	//循环遍历之前加上非空判断
	if (zqtEntity && zqtEntity.length >= 0) {
		zqtEntity.forEach((item) => {
			// 判断表格中是否已经有该条件
			const found = tableData.value.find(element => element.condition === item.condition);
			// 已经存在该条件
			if (found) {
				const findConlum = tableColumns.value.find(col => col.cbrsId === item.projectId)
				if (findConlum) {
					found[findConlum.filedProp] = item.ciValue
				}
				// found['dynamicField-' + item.cbrmColumn] = item.ciValue
				found.cbrmIds.push(item.cbrmId)
				found.origin.push(item)
			}
			// 不存在
			else {
				const data = {
					isEdit: false,
					condition: item.condition,
					defaultData: item.defaultData,
					cbrmIds: [],
					origin: []
				}
				// data['dynamicField-' + item.cbrmColumn] = item.ciValue
				const findConlum = tableColumns.value.find(col => col.cbrsId === item.projectId)
				if (findConlum) {
					data[findConlum.filedProp] = item.ciValue
				}
				data.cbrmIds.push(item.cbrmId)
				data.origin.push(item)
				tableData.value.push(data);
			}
		});
	}
}
//砖砌体结构抗力修正系数Ci值添加  新增列
const onAddColumn = async () => {
	const cbrsColumns = tableColumns.value.map(item => item.cbrsColumn)
	const maxColumns = cbrsColumns.reduce((a, b) => Math.max(a, b), -Infinity);
	const cbrmColumn = maxColumns + 1

	ElMessageBox.confirm('确认新增列, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		const paramsp = {
			"zqtEntity": [
				// {
				//     "condition": "",
				//     "cbrmColumn": cbrmColumn,
				//     "ciValue": ""
				// },
			],
			"dynamicFieldsEntity": [
				{
					"cbrsColumn": cbrmColumn,
					"cbrsKey": "砖砌体结构抗力修正系数Ci值",
					"info": '新增列'
				}
			]
		}
		await saveZqtCi(paramsp).then((res) => {
			if (res.code === 200) {
				ElMessage({
					type: 'success',
					message: '添加成功!'
				});
				onSearch()
			}
		}).catch(err => {
			ElMessage({
				type: 'info',
				message: '添加失败'
			});
		});
	}).catch(err => {
		// console.log(err);
		ElMessage({
			type: 'info',
			message: '已取消新增'
		});
	});
}

//砖砌体结构抗力修正系数Ci值添加行或更新保存行，存在同名condition是更新，不存在是添加
const onAddOrUpdateRows = async (row) => {
	// if (row.isNew) { // 如果是新增加行，条件名不能重复，要不就是更新了（后台逻辑这么写的）
	//     // 判断表格中是否已经有该条件
	//     console.log(row)
	//      const found = tableData.value.slice(0,tableData.value.length-2).find(element => element.condition === row.condition);
	//     console.log('console.log(row)',found)
	//     if (found) {
	//         ElMessage({
	//             type: 'warning',
	//             message: '已经存在同名条件!'
	//         });
	//         return;
	//     }
	// }
	const zqtEntity = [];
	if (row.origin?.length > 0) {
		// row.origin.forEach(item => {
		//     const findConlum = tableColumns.value.find(col => col.cbrsId === item.projectId)
		//     let ciValue = null
		//     if (findConlum) {
		//         ciValue = row[findConlum.filedProp]
		//     }
		//     zqtEntity.push({
		//         cbrmId: item.cbrmId,
		//         condition: row.condition,
		//         cbrmColumn: item.cbrmColumn,
		//         ciValue: ciValue,
		//         projectId: item.projectId
		//     })
		// })
		tableColumns.value.forEach(col => {
			const findOrigin = row.origin.find(item => col.cbrsId === item.projectId)
			if (findOrigin) {
				zqtEntity.push({
					cbrmId: findOrigin.cbrmId,
					condition: row.condition,
					// cbrmColumn: findOrigin.cbrmColumn,
					ciValue: row[col.filedProp],
					projectId: col.cbrsId
				})
			} else {
				zqtEntity.push({
					// cbrmId: item.cbrmId,
					condition: row.condition,
					// cbrmColumn: item.cbrmColumn,
					ciValue: row[col.filedProp],
					projectId: col.cbrsId
				})
			}
		})
	} else {
		tableColumns.value.forEach(item => {
			zqtEntity.push({
				condition: row.condition,
				cbrmColumn: item.cbrsColumn,
				ciValue: row['dynamicField-' + item.cbrsColumn],
				projectId: item.cbrsId
			})
		})
	}
	const paramsp = {
		zqtEntity  // 等价于zqtEntity：zqtEntity
	}
	await saveZqtCi(paramsp).then((res) => {
		if (res.code === 200) {
			row.isEdit = false
			row.isNew = false
			ElMessage({
				type: 'success',
				message: '保存成功!'
			});
		}
	}).catch(err => {
		console.log(err);
	});
	onSearch()
}

// 删除行
const onDeleteRows = async (ids, arrangeIds) => {
	if ((!ids || ids.length <= 0) && (!arrangeIds || arrangeIds.length <= 0)) {
		ElMessage({
			type: 'warning',
			message: '请选中数据!'
		});
		return
	}
	const paramsp = { zqtIds: ids, arrangeIds: arrangeIds }
	await deleteZqtCiById(paramsp).then((res) => {
		if (res.code === 200) {
			ElMessage({
				type: 'success',
				message: '删除成功!'
			});
		}
	}).catch(err => {
		ElMessage({
			type: 'error',
			message: '删除失败!'
		});
	})
}

// 挂载
onMounted(() => {
	onSearch()
});
</script>

<style lang="scss" scoped>
</style>